<template>

  <div id="components-layout-demo-basic">

    <a-layout>
<!--      页眉部分-->
      <a-layout-header>
        <div class="gutter-example">
          <a-row :gutter="16">
            <a-col class="gutter-row" :span="2">
              <div class="gutter-box">
                <span>姓名：</span>
                <a-input placeholder="姓名" v-model="query.name" />
              </div>
            </a-col>
            <a-col class="gutter-row" :span="5">
              <div class="gutter-box">
                <span>实习开始日期：</span>
<!--      这个双选的时间只有一个值，但提交到后台需要两个值，因此该值跟internship绑定一起，
           而每次提交时都判断该值是否选择了时间，
            如果选择，将其时间封装到query查询条件中，如果没有值，也记得把query的时间清空          -->
                <a-range-picker
                  @change="onChange"
                  v-model="internship"
                  :format="dateFormat"/>
              </div>
            </a-col>
            <a-col class="gutter-row" :span="2">
              <div class="gutter-box">
                <span>关键字：</span>
                <a-select  v-model="query.key" style="width: 100px;">
                  <a-select-option value="native_place">
                    籍贯
                  </a-select-option>
                  <a-select-option value="vx">
                    微信
                  </a-select-option>
                  <a-select-option value="qq">
                    QQ
                  </a-select-option>
                  <a-select-option value="school">
                    学校
                  </a-select-option>
                  <a-select-option value="education">
                    学历
                  </a-select-option>
                  <a-select-option value="sex">
                    性别
                  </a-select-option>
                </a-select>
              </div>
            </a-col>
            <a-col class="gutter-row" :span="2">
              <div class="gutter-box">
                <span>搜索：</span>
                <a-input  placeholder="搜索" v-model="query.value" />
              </div>
            </a-col>
            <a-col class="gutter-row" :span="13" style="text-align: left;">
              <div class="gutter-box">
                <a-button type="primary"  class="head_group_button" @click="queryCondition" style="float: left;">查询</a-button>
                <a-upload style="float: left;"
                  name="file"
                  :multiple="true"
                  :action="BASE_API+'internship/internship/excelImport'"
                  :headers="headers"
                  :before-upload="beforeUpload"
                  @change="handleUploadChange"
                >
                  <a-button type="primary"  class="head_group_button" v-has="'internship:add'" v-show="isManager">导入数据</a-button>
                </a-upload>
                <a-button type="primary"  class="head_group_button" @click="exportExcel">导出数据</a-button>

                <a-button type="primary"  class="head_group_button" @click="bi">访问bi,有标题和没标题</a-button>

                <a-button type="primary"  class="head_group_button" v-has="'internship:add'" v-show="isManager" @click="add" style="position: absolute;  right: 0px;" >添加</a-button>
                <!--  选中checked时显示的按钮   -->
                <div style="position: absolute;  right: 100px; top: 25px;">
                  <a-button type="danger" ghost id="batchDeleteId" :disabled="!hasSelected" :loading="loading" @click="batchDelete" v-has="'internship:delete'" v-show="isManager">
                    批量删除
                  </a-button>
                </div>
              </div>
            </a-col>

          </a-row>
        </div>

        <div>
          <hr color="#00a0e9"/>
        </div>

      </a-layout-header>


<!--      中间部分-->
      <a-layout-content>

        <div>
          <a-table
            :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
            :columns="columns"
            :data-source="list"
            rowKey='id'
            :pagination="false"
            :scroll="{ y: heightTable }"
            @change="handleTableChange"
          >
<!--                        size="middle"-->
            <template  slot="operation" slot-scope="text, record">
              <a @click="handleInfo(record.id)" style="margin-right: 10px;" v-show="!isManager">查看</a>
              <a @click="handleEdit(record.id)" style="margin-right: 10px;" v-has="'internship:modify'" v-show="isManager">编辑</a>
              <a type="danger" @click="handleDelete(record.id)" v-has="'internship:delete'" v-show="isManager">删除</a>
            </template >
          </a-table>
        </div>

      </a-layout-content>

<!--      页脚部分-->
      <a-layout-footer >
        <a-pagination
          show-quick-jumper
          v-model="pagination.page"
          :page-size-options="pagination.pageSizeOptions"
          :total="pagination.total"
          show-size-changer
          :page-size="pagination.pageSize"
          @change="onChangePagination"
          @showSizeChange="onShowSizeChange"
        >
          <template slot="buildOptionText" slot-scope="props">
            <span v-if="props.value !== '100'">{{ props.value }}条/页</span>
<!--            <span v-if="props.value === '50'">全部</span>-->
          </template>
        </a-pagination>

      </a-layout-footer>
    </a-layout>

  </div>

</template>

<script>

    import {getAction,postAction,putAction,deleteAction,batchDeleteAction} from '@/api/manage'
    import {format} from "../../utils/dateFormat"
    import {API} from '@/api/base_api'
    //给Date添加format方法，转换格式
    Date.prototype.format = format;

    //table 的列
    const columns = [
        {
            title: '姓名',
            dataIndex: 'name',
            width: '10%',
            scopedSlots: { customRender: 'name' },
        },
        {
            title: '所属学校',
            dataIndex: 'school',
            width: '15%',
            scopedSlots: { customRender: 'school' },
        },
        {
            title: '手机号码',
            dataIndex: 'phone',
            width: '15%',
            scopedSlots: { customRender: 'phone' },
        },
        {
            title: '实习日期',
            dataIndex: 'startDate',
            width: '15%',
            scopedSlots: { customRender: 'startDate' },
        },
        {
            title: '年龄',
            dataIndex: 'age',
            width: '5%',
            scopedSlots: { customRender: 'age' },
        },
        {
            title: '籍贯',
            dataIndex: 'nativePlace',
            width: '10%',
            scopedSlots: { customRender: 'nativePlace' },
        },
        {
            title: '居住地',
            dataIndex: 'address',
            width: '10%',
            scopedSlots: { customRender: 'address' },
        },
        {
            title: '操作',
            dataIndex: 'operation',
            scopedSlots: { customRender: 'operation' },
            align: "center",
            width: 170
        },
    ];

    //已占领的高度
    let occupyHeight = 380;

    export default {
        name: "Internship",
        data() {
            return {
                BASE_API:null,
                //table高度
                heightTable:document.documentElement.clientHeight-occupyHeight,
                //分页
                pagination: {
                    page:1,//当前页数
                    pageSize: 10,//每页中显示10条数据
                    total: 0,
                    showSizeChanger: true,
                    pageSizeOptions: ['10', '20', '30', '40', '50'],//每页中显示的数据
                    showTotal: total => `共有 ${total} 条数据`,  //分页中显示总的数据
                },
                //上传文件
                headers: {
                    authorization: 'authorization-text',
                },
                //list集合数据
                list:[],
                // 日期格式
                dateFormat: 'YYYY-MM-DD',
                //开始实习时间
                internship:null,
                //是否是管理页面
                isManager:false,
                //查询条件
                query:{
                    name:null,
                    start:null,
                    end:null,
                    key:null,
                    value:null
                },
                //table的列表结构
                columns,
                //checked的选择数量
                selectedRowKeys: [], // Check here to configure the default column
                loading: false,
            };
        },
        watch: {
            // heightTable(newValue, oldValue) {
            //     if(newValue) {
            //         console.log(this.heightTable);
            //     }
            // }
            $route(to,from){
                if(to.path.indexOf("manager")!=-1){
                    this.isManager = true;
                }else{
                    this.isManager = false;
                }
            }
        },
        // mounted() {
        //     //获取高度值
        //     window.onresize = () => {
        //         this.heightTable = document.documentElement.clientHeight-occupyHeight;
        //         console.log("intervship list height = ",this.heightTable);
        //     }
        // },
        computed: {
            //每次点击checked时，触发方法，判断是否选中一条，只要选中了就显示批量删除按钮
            hasSelected() {
                return this.selectedRowKeys.length > 0;
            },
        },
        methods: {
            bi(){
                // getAction("http://localhost:8070/zuul/sys/role/queryTreeList").then(resp =>{
                //    console.log("权限 = 》",resp)
                // })
                // getAction("http://localhost:8070/zuul/sys/permission/list").then(resp =>{
                //    console.log("权限 = 》",resp)
                // })
                // getAction("http://localhost:8070/zuul/sys/permission/getUserPermissionByToken").then(resp =>{
                //    console.log("权限 = 》",resp)
                // })
                getAction("/internship/internship/getCheckCode").then(resp =>{
                   console.log("权限 = 》",resp)
                })

            },
            //路由跳转到添加页面
            add(){
                // this.$router.push("./details");
                this.$emit('router-pane',2,0,false)
            },
            //查看功能
            handleInfo(id){
                this.$emit('router-pane',2,id,true)
            },
            //编辑
            handleEdit(id ) {
                // this.$router.push("./details/"+id);
                this.$emit('router-pane',2,id,false)
            },
            //删除
            handleDelete(id) {
                let that = this;
                this.$confirm({
                    title: '警告！',
                    content: '是否删除数据？',
                    okText: '确定',
                    okType: 'danger',
                    cancelText: '取消',
                    onOk() {
                        that.loading = true;
                        deleteAction("/internship/internship/delete/"+id).then(resp =>{
                            that.init();
                            console.log("删除数据完成",resp);
                            that.loading = false;
                        }).catch(error=>{
                            console.log("删除数据错误",error);
                        })
                    },
                    onCancel() {
                        console.log('Cancel');
                    },
                });
            },
            // table批量删除
            batchDelete() {
                let that = this;
                this.$confirm({
                    title: '是否删除多条数据?',
                    content: '该操作将永久的删除多条数据',
                    okText: '确定',
                    okType: 'danger',
                    cancelText: '取消',
                    onOk() {
                        that.loading = true;
                        batchDeleteAction("/internship/internship/delete/batch",that.selectedRowKeys).then(resp =>{
                            that.init();
                            console.log("删除数据完成",resp);
                            that.loading = false;
                        }).catch(error=>{
                            console.log("删除数据错误",error);
                        })
                    },
                    onCancel() {
                        console.log('Cancel',that.selectedRowKeys);
                    },
                });
            },
            //初始化加载list数据
            init(){
                this.BASE_API = API();
                let that = this;
                postAction(`/internship/internship/list/${this.pagination.page}/${this.pagination.pageSize}`,this.query).then(function(resp){
                    that.list = resp.result.records;
                    that.pagination.total  = resp.result.total;
                    // that.pagination.page = res.result.current;
                    // that.pagination.pageSize = res.result.size;
                }).catch(function(error){
                    console.log(error);
                })
            },
            //导出excel
            exportExcel(){
                let that = this;
                getAction("/internship/internship/excelExport").then(resp=>{
                    console.log("文档路径",resp)
                    window.location.href = that.BASE_API+resp.message;
                }).catch(error=>{
                    console.log("文档路径",error)
                })
            },
            //上传文件前先判断条件是否满足
            beforeUpload(file) {
                let str = file.name.split('.');
                const isExcel = str[str.length-1] === 'xls' || str[str.length-1] === 'xlsx';
                if (!isExcel) {
                    this.$message.error('请上传excel格式文件！');
                }
                const isLt2M = file.size / 1024 / 1024 /1024 < 1;
                if (!isLt2M) {
                    this.$message.error('excel不得超过10Mb!');
                }
                return isExcel && isLt2M;
            },
            //上传excel文档
            handleUploadChange(info) {
                if (info.file.status !== 'uploading') {
                    console.log(info.file, info.fileList);
                }
                if (info.file.status === 'done') {
                    this.$message.success(`${info.file.name} 上传文件成功`);
                    this.init();
                } else if (info.file.status === 'error') {
                    this.$message.error(`${info.file.name} 上传失败`);
                }
            },
            // 日期
            onChange(date, dateString) {
                console.log("时间 = 》 ",date,dateString)
                this.query.start = dateString[0];
                this.query.end = dateString[1];
            },
            //选中checked时触发方法
            onSelectChange(selectedRowKeys) {
                console.log('selectedRowKeys changed: ', selectedRowKeys);
                this.selectedRowKeys = selectedRowKeys;
            },
            //查询条件（list数据）
            queryCondition(){
                console.log("internship",this.internship)
                this.init();
            },
            //分页触发当前页
            onChangePagination(current){
                this.pagination.page = current;
                this.init();
            },
            //分页大小
            onShowSizeChange(current, pageSize) {
                this.pagination.page = current;//当前页
                this.pagination.pageSize = pageSize;//页数大小
                this.init();
            },
            //分页  -- 这个是table自带的分页，但是已经取消自带分页
            handleTableChange(pagination) {
                this.pagination.page = pagination.current;
                this.pagination.pageSize = pagination.pageSize;
                // this.page = pagination.current;
                // this.size = pagination.pageSize;
                this.init();
            },
            //加载高度
            initLoadHeight(height){
                this.heightTable = height-(occupyHeight) ;
            },
        },created() {
          this.init();
            if(this.$route.path.indexOf("manager")!=-1){
                this.isManager = true;
            }else{
                this.isManager = false;
            }
        },

    }
</script>

<style scoped>
  /*table*/
  .editable-row-operations a {
    margin-right: 8px;
  }
  /*button*/
  .head_group_button{
    margin: 0 10px;
    margin-top: 20px;
  }
  /*span*/
  .gutter-example span{
    font-weight: bold;
    font-size: 14px;
    word-break:normal;
    width:auto;
    display:block;
    white-space:pre-wrap;
    word-wrap : break-word ;
    overflow: hidden ;
  }
  /* 栅格系统 */
  .gutter-example >>> .ant-row > div {
    background: transparent;
    border: 0;
  }
  /*查询、导出、导入按钮的间距*/
  .gutter-box {
    margin: 5px 0;
  }

  /*layout布局*/
  #components-layout-demo-basic {
    text-align: center;
  }
  #components-layout-demo-basic .ant-layout-header {
    background-color:transparent;
    height: 100px;
    line-height: 1.5;
  }
  #components-layout-demo-basic .ant-layout-footer {
    line-height: 1.5;

    /*position: absolute;*/
    /*left: 50%;*/
    /*bottom: 2%;*/
    /*transform: translateX(calc(-50% + 100px));*/
  }
  #components-layout-demo-basic .ant-layout-content {
    /*color: #fff;*/
    min-height: 120px;
    line-height: 120px;
  }
  #components-layout-demo-basic > .ant-layout {
    margin-bottom: 48px;
  }
  #components-layout-demo-basic > .ant-layout:last-child {
    margin: 0;
  }

  /*分页*/
  #components-pagination-demo-mini .ant-pagination:not(:last-child) {
    /*margin-bottom: 10px;*/
  }

</style>